import { setLock, getLock, removeLock, getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'
import defaultSettings from '@/settings'
import jnpf from '@/utils/jnpf'
import { login, getDynamicMenu } from '@/api/login.js'
import md5 from 'js-md5'
const define = require('@/utils/define')

const state = {
  token: getToken(),
  isLock: getLock() || 0,
  isLeaveToast: true,
  menuList: [],
  leftMenuList: [],
  userInfo: {
    headIcon: '/api/file/Image/userAvatar/207.jpg'
  },
  permissionList: [],
  loginLoading: false,
  socket: ''
}

const mutations = {
  SET_TOAST: (state, data) => {
    state.isLeaveToast = data
  },
  SET_SOCKET: (state, socket) => {
    state.socket = socket
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_MENULIST: (state, menuList) => {
    state.menuList = menuList
  },
  SET_LEFTMENULIST: (state, leftMenuList) => {
    state.leftMenuList = leftMenuList
  },
  SET_USERINFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  SET_USERINFO_HEADICON: (state, headIcon) => {
    console.log('headIcon')
    // state.userInfo.headIcon = headIcon
  },
  SET_USERINFO_USERNAME: (state, userName) => {
    state.userInfo.userName = userName
  },
  SET_USERINFO_PORTALID: (state, portalId) => {
    state.userInfo.portalId = portalId
  },
  SET_PERMISSION_LIST: (state, permissionList) => {
    state.permissionList = permissionList
  },
  SET_LOCK: (state, isLock) => {
    state.isLock = isLock
  },
  SET_LOGIN_LOADING: (state, loginLoading) => {
    state.loginLoading = loginLoading
  },
  SET_USERINFO_SIGNIMG: (state, signImg) => {
    state.userInfo.signImg = signImg
  }
}

const actions = {
  // 锁屏
  setLock({ commit }) {
    commit('SET_LOCK', 1)
    setLock(1)
  },
  clearLock({ commit }) {
    commit('SET_LOCK', '')
    removeLock()
  },
  unlock({ dispatch }, userInfo) {
    const { account, password } = userInfo
    return new Promise((resolve, reject) => {
      dispatch('clearLock')
      resolve()
      // unlock({ account: account.trim(), password: md5(password) }).then(response => {
      //   dispatch('clearLock')
      //   resolve()
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },
  // user login
  login({ dispatch }, userInfo) {
    const { account, password, code, timestamp, origin, jnpf_ticket } = userInfo
    return new Promise((resolve, reject) => {
      const encryptPassword = jnpf.aesEncryption.encrypt(md5(password))
      login({ id: account, password: password })
        .then(res => {
          const data = require('../../json/login.json')
          dispatch('setToken', res.data.token).then(() => {
            resolve(data)
          })
        })
        .catch(error => {
          reject(error)
        })
      // login(qs.stringify({
      //   account: account.trim(),
      //   password: encryptPassword,
      //   jnpf_ticket: jnpf_ticket,
      //   origin,
      //   code,
      //   timestamp,
      //   grant_type: 'password'
      // })).then(response => {
      // dispatch('setToken', data).then(() => {
      //   resolve(data)
      // })
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },
  // 保存token
  setToken({ commit }, data) {
    return new Promise((resolve, reject) => {
      setToken('Bearer ' + data)
      // const layoutList = ['classic', 'functional', 'plain', 'blend']
      // const layoutType = data.theme && layoutList.indexOf(data.theme) > -1 ? data.theme : 'classic'
      commit('SET_TOKEN', 'Bearer ' + data)
      // commit('settings/CHANGE_SETTING', { key: 'layoutType', value: layoutType }, { root: true })
      resolve(data)
    })
  },
  // 获取用户信息
  getInfo({ commit }) {
    var menuid = 1
    var parenid = 0
    return new Promise((resolve, reject) => {
      getDynamicMenu({ token: getToken(),systype:"L" })
        .then(res => {
          const sysinfo = require('../../json/menu.json')
          if (!res) reject('验证失败，请重新登录。')
          const menuList = res.data.list
          if (!menuList.length) {
            reject('您的权限不足，请联系管理员')
            return false
          }
          const routerList = []
          function setData(list, id) {
            for (let i = 0; i < list.length; i++) {
              const e = list[i]
              const name = e.meta.title
              e.vueName = name
              if (e.children != null) {
                e.hasChildren = true
                parenid++
                e.id = parenid
                e.type = 1
                setData(e.children, parenid)
              } else {
                e.hasChildren = false
                e.parentId = parenid
                e.type = 2
              }
              if (e.children == null) {
                const path = e.component
                // if (path.indexOf('?') > -1) path = path.split('?')[0]
                // e.path = '/' + e.urlAddress
                const newObj = {
                  path: e.path,
                  component: (resolve) => require([`@/views/${e.component}`], resolve),
                  name: e.name,
                  meta: {
                    title: name,
                    icon: 'el-icon-s-shop',
                    zhTitle: name,
                    modelId: menuid + 1
                  }
                }
                routerList.push(newObj)
              }
            }
          }
          setData(menuList)
          commit('SET_MENULIST', menuList)
          commit('SET_USERINFO', sysinfo.data.userInfo)
          commit('SET_PERMISSION_LIST', sysinfo.data.permissionList)
          const sysConfigInfo = sysinfo.data.sysConfigInfo || defaultSettings.sysConfig
          commit('settings/CHANGE_SETTING', { key: 'sysConfig', value: sysConfigInfo }, { root: true })
          resolve(routerList)
        })
        .catch(error => {
          reject(error)
        })
    })
  },
  // user logout
  logout({ dispatch }) {
    return new Promise((resolve, reject) => {
      dispatch('resetToken').then(() => {
        resolve()
      })
      // logout().then(() => {
      //   dispatch('resetToken').then(() => {
      //     resolve()
      //   })
      // }).catch(error => {
      //   reject(error)
      // })
    })
  },
  // remove token
  resetToken({ commit, state, dispatch }) {
    return new Promise(resolve => {
      commit('SET_TOKEN', '')
      if (state.socket) {
        state.socket.close()
        commit('SET_SOCKET', null)
      }
      resetRouter()
      // reset visited views and cached views
      dispatch('tagsView/delAllViews', null, { root: true })
      commit('SET_MENULIST', [])
      commit('SET_USERINFO', {})
      commit('SET_PERMISSION_LIST', [])
      commit('SET_LOGIN_LOADING', false)
      commit('generator/SET_COMPANY_TREE', [], { root: true })
      commit('generator/SET_DEP_TREE', [], { root: true })
      commit('base/SET_DICTIONARY_LIST', [], { root: true })
      removeToken()
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
